<template>
  <fs-page class="fs-page-warp">
    <el-row class="demo-nest" :gutter="0">
      <el-col :span="4">
        <el-tree
          v-if="roleList.length > 0"
          :data="roleList"
          default-expand-all
          ref="treeRef"
          node-key="id"
          highlight-current
          :props="defaultProps"
          @node-click="roleClick"
        >
          <template #default="{ data }">
            {{ data.name }}
          </template>
          <template #render-content="{ node, data }">
            <span :class="{ 'is-selected': node.checked }">{{
              data.name
            }}</span>
          </template>
        </el-tree>
      </el-col>
      <el-col :span="20">
        <fs-crud ref="crudRef" v-bind="crudBinding">
          <template #form_deptId="scope">
            <el-cascader
              :disabled="scope.mode === 'view'"
              class="w-full"
              v-model="scope.form.deptId"
              :options="deptIdList"
              :props="{
                value: 'id',
                label: 'label',
                emitPath: false,
                checkStrictly: true
              }"
              clearable
              filterable
              placeholder="请选择上级部门"
            >
              <template #default="{ node, data }">
                <span>{{ data.label }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </template>
        </fs-crud>
      </el-col>
    </el-row>
  </fs-page>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from "vue";
import {
  AddReq,
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  DelReq,
  dict,
  EditReq,
  useFs,
  UserPageQuery,
  UserPageRes
} from "@fast-crud/fast-crud";
import { ElTree } from "element-plus";
import { hasAuth } from "@/router/utils";

import {
  putV1OmsStaff,
  postV1OmsStaff,
  getV1OmsStaffPage,
  getV1OmsStaffDetail,
  deleteV1OmsStaffDetail
} from "@/api/oms/staff";
import { getV1OmsDeptTree } from "@/api/oms/dept";
import { convertTreeToCustomFields } from "@/utils/tree";
import { getV1OmsRoleSelector } from "@/api/oms/role";
import { REGEXP_PWD } from "@/views/login/utils/rule";
//此处为crudOptions配置
const createCrudOptions = function ({
  crudExpose
}: CreateCrudOptionsProps): CreateCrudOptionsRet {
  //本地模拟后台crud接口方法 ----开始

  const pageRequest = async (query: UserPageQuery): Promise<UserPageRes> => {
    const { data } = await getV1OmsStaffPage({
      ...query.page,
      ...query.form,
      ...query.sort,
      pageNumber: query.page.currentPage
    });
    return {
      records: data.result,
      currentPage: query.page.pageNumber,
      pageSize: query.page.pageSize,
      total: data.total
    };
  };

  const editRequest = async ({ form, row }: EditReq) => {
    const { data } = await putV1OmsStaff({ id: row.id, ...form });
    return data.data;
  };

  const delRequest = async ({ row }: DelReq) => {
    const { data } = await deleteV1OmsStaffDetail(row);
    return data.data;
  };

  const addRequest = async ({ form }: AddReq) => {
    const { data } = await postV1OmsStaff(form);
    return data.data;
  };
  const onRowBtnClick = async rowHandle => {
    if (rowHandle.initialForm.id) {
      const { data } = await getV1OmsStaffDetail({
        id: rowHandle.initialForm.id
      });
      crudExpose.setFormData(data.data);
    }
  };
  return {
    crudOptions: {
      request: {
        pageRequest,
        editRequest,
        delRequest,
        addRequest
      },
      form: {
        wrapper: {
          is: "el-drawer",
          size: "800px",
          onOpen: onRowBtnClick
        },
        initialForm: {},
        labelPosition: "right",
        labelWidth: "120px" //表单label宽度
      },
      actionbar: {
        buttons: {
          add: {
            show: hasAuth("oms:staff:add"),
            click: () => {
              const search = crudExpose.getSearchFormData();
              crudExpose.openAdd({
                row: {
                  deptId: search.deptId,
                  sex: "1",
                  status: true,
                  roleList: []
                }
              });
            }
          }
        }
      },
      search: { autoSearch: false },
      rowHandle: {
        fixed: "right",
        buttons: {
          view: {
            show: hasAuth("oms:staff:detail"),
            type: "success",
            plain: true
          },
          edit: { show: hasAuth("oms:staff:update"), plain: true },
          remove: { show: hasAuth("oms:staff:remove"), plain: true }
        }
      },
      columns: {
        email: {
          title: "邮箱",
          type: "text",
          search: { show: false },
          column: {
            show: false,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: { show: false },
          addForm: { show: false }
        },
        phone: {
          title: "手机号",
          type: "text",
          search: { show: false },
          column: {
            show: false,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: { show: false },
          addForm: { show: false }
        },
        createTime: {
          title: "创建时间",
          type: "date",
          search: { show: false },
          column: {
            show: false,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: { show: false },
          addForm: { show: false }
        },
        deptId: {
          title: "所属部门",
          type: "dict-cascader",
          form: {
            component: {
              filterable: true,
              // props下配置属性跟配置在component下是一样的效果，而el-cascade下也有一个叫props的属性，所以需要配置两层
              props: { props: { checkStrictly: true } }
            }
          },
          dict: dict({
            isTree: true,
            label: "label",
            value: "id",
            getData: async () => {
              // 覆盖全局获取字典请求配置
              const { data } = await getV1OmsDeptTree();
              return convertTreeToCustomFields(
                [{ id: "0", name: "lafPureAdmin", children: data.result }],
                {
                  id: "id",
                  parent: "parentDeptId",
                  name: "name"
                }
              );
            }
          }),
          search: { show: false },
          column: {
            show: false,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: { rules: [{ required: true, message: "请输入部门ID" }] },
          addForm: { rules: [{ required: true, message: "请输入部门ID" }] }
        },
        id: {
          title: "用户ID",
          type: "text",
          search: { show: false },
          column: {
            show: false,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: { show: false },
          addForm: { show: false }
        },
        nickName: {
          title: "用户昵称",
          type: "text",
          search: { show: true },
          column: {
            show: true,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: { rules: [{ required: true, message: "请输入用户昵称" }] },
          addForm: { rules: [{ required: true, message: "请输入用户昵称" }] }
        },
        username: {
          title: "登陆账号",
          type: "text",
          search: { show: false },
          column: {
            show: true,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: { show: false },
          addForm: { rules: [{ required: true, message: "请输入用户昵称" }] }
        },
        password: {
          title: "密码",
          type: "text",
          search: { show: false },
          column: {
            show: false,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          viewForm: { show: false },
          editForm: { show: false },
          addForm: {
            rules: [
              {
                required: true,
                validator: (rule, value, callback) => {
                  if (value === "") {
                    callback(new Error("请输入密码"));
                  } else if (!REGEXP_PWD.test(value)) {
                    callback(
                      new Error(
                        "密码格式应为8-18位数字、字母、符号的任意两种组合"
                      )
                    );
                  } else {
                    callback();
                  }
                }
              }
            ]
          }
        },

        roleList: {
          title: "角色列表",
          type: "dict-select",
          form: {
            component: {
              multiple: true,
              "show-checkbox": true
            }
          },
          dict: dict({
            isTree: true,
            label: "name",
            value: "id",
            getData: async () => {
              // 覆盖全局获取字典请求配置
              const { data } = await getV1OmsRoleSelector();
              return data.result;
            }
          }),
          search: { show: false },
          column: {
            show: false,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: { rules: [{ required: true, message: "请选择项目权限" }] },
          addForm: {
            value: [],
            rules: [{ required: true, message: "请选择项目权限" }]
          }
        },
        sex: {
          title: "用户性别",
          type: "dict-radio",
          search: { show: false },
          column: {
            show: true,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          dict: dict({
            data: [
              { value: "1", label: "男" },
              { value: "2", label: "女" },
              { value: "3", label: "未知" }
            ]
          }),
          editForm: { rules: [{ required: true, message: "请选择用户性别" }] },
          addForm: {
            value: "0",
            rules: [{ required: true, message: "请选择用户性别" }]
          }
        },
        status: {
          title: "帐号状态",
          type: "dict-radio",
          search: { show: true },
          column: {
            show: true,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          dict: dict({
            data: [
              { value: false, label: "停用" },
              { value: true, label: "正常" }
            ]
          }),
          editForm: { rules: [{ required: true, message: "请选择帐号状态" }] },
          addForm: {
            value: true,
            rules: [{ required: true, message: "请选择帐号状态" }]
          }
        },
        updated_at: {
          title: "编辑时间",
          type: "date",
          search: { show: false },
          column: {
            show: true,
            resizable: true,
            minWidth: 140,
            align: "center",
            width: 200,
            component: { format: "YYYY-MM-DD HH:mm:ss" }
          },
          editForm: { show: false },
          addForm: { show: false }
        }
      }
    }
  };
};

//此处为组件定义
export default defineComponent({
  name: "omsstaff",
  setup() {
    const deptIdList = ref([]);
    // 演示自定义变量传递, 将会传递给createCrudOptions
    const customValue: Object = {};
    //  =======你可以简写为下面这一行========
    const { crudRef, crudBinding, crudExpose } = useFs({
      createCrudOptions,
      context: customValue
    });
    const treeRef = ref<InstanceType<typeof ElTree>>();

    const roleList = ref([]);
    const init = async () => {
      const { data } = await getV1OmsDeptTree();
      deptIdList.value = convertTreeToCustomFields(
        [{ id: "0", name: "lafPureAdmin", children: data.result }],
        {
          id: "id",
          parent: "parentDeptId",
          name: "name"
        }
      );
    };
    // 页面打开后获取列表数据
    onMounted(async () => {
      const { data } = await getV1OmsDeptTree();
      roleList.value = data.result;
      console.log(data, "data>>>");
      setTimeout(() => {
        const rootNode = treeRef.value!.getNode(data.result[0].children[0].id);
        treeRef.value!.setCurrentKey(rootNode.key);
      }, 100);
      crudExpose.setSearchFormData({
        form: { deptId: data.result[0].children[0].id }
      });
      await init();
      crudExpose.doRefresh();
    });
    const roleClick = item => {
      console.log(item);
      crudExpose.doSearch({
        form: {
          deptId: item.id
        }
      });
    };
    const defaultProps = {
      children: "children",
      label: "name"
    };
    return {
      deptIdList,
      treeRef,
      defaultProps,
      roleClick,
      roleList,
      crudBinding,
      crudRef
    };
  }
});
</script>
<style lang="scss">
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  color: var(--el-menu-active-color);
}

.demo-nest {
  height: 100%;
}
</style>
